/*
 *  Copyright (c) 2024-2024, Ai东 (abc-127@live.cn).
 *
 *  Licensed under the Apache License, Version 2.0 (the "License").
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and limitations under the License.
 *
 */

package cn.mybatis.mp.core.mybatis.mapper.mappers.utils;

import cn.mybatis.mp.core.db.reflect.TableInfo;
import cn.mybatis.mp.core.mybatis.mapper.BasicMapper;
import cn.mybatis.mp.core.sql.executor.Query;
import cn.mybatis.mp.core.sql.util.WhereUtil;
import db.sql.api.Getter;
import db.sql.api.impl.cmd.basic.Table;

import java.util.Collection;
import java.util.Objects;

public class SaveOrUpdateMethodUtil {

    public static <T> int saveOrUpdate(BasicMapper basicMapper, TableInfo tableInfo, T entity, boolean allFieldForce, Getter<T>... forceFields) {
        Class<?> entityType = entity.getClass();
        if (tableInfo.getIdFieldInfos().isEmpty()) {
            throw new RuntimeException(entityType.getName() + " has no id");
        }
        Object id;
        try {
            id = tableInfo.getIdFieldInfos().get(0).getReadFieldInvoker().invoke(entity, null);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

        if (Objects.isNull(id)) {
            return SaveMethodUtil.save(basicMapper, tableInfo, entity, allFieldForce, forceFields);
        }

        Query<T> query = Query.create();
        query.$().cacheTableInfo(tableInfo);
        Table table = query.$(entityType);
        query.select1().from(table);

        WhereUtil.appendIdWhereWithEntity(query.$where(), tableInfo, entity);
        boolean exists = basicMapper.exists(query);
        if (exists) {
            return UpdateMethodUtil.update(basicMapper, tableInfo, entity, allFieldForce, forceFields);
        } else {
            return SaveMethodUtil.save(basicMapper, tableInfo, entity, allFieldForce, forceFields);
        }
    }

    public static <T> int saveOrUpdate(BasicMapper basicMapper, TableInfo tableInfo, Collection<T> list, boolean allFieldForce, Getter<T>... forceFields) {
        if (Objects.isNull(list) || list.isEmpty()) {
            return 0;
        }
        int cnt = 0;
        for (T entity : list) {
            cnt += saveOrUpdate(basicMapper, tableInfo, entity, allFieldForce, forceFields);
        }
        return cnt;
    }
}
